﻿
//Helper Functions
function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

function checkBrowserSupport()
{
    var name = navigator.appName;

    if (name == "Microsoft Internet Explorer") return true;
    else return false;
}

function checkVirtualEarthApi()
{
    if (self.ve_api) return true;
    else return false;
}

function loadVirtualEarthApi() 
{
    if (self.ve_api) return;
    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement('script');
    script.id = 've_api';
    script.type = 'text/javascript';
    script.src = "http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1";
    head.appendChild(script);
}

/*
La Virtual map è una mappa di Virtual Earth che risiede nascosta in background e che può
essere embeddata nei pop-up di google maps.

Ce ne deve essere solo una per sessione!
*/
MapControl2.AAAVirtualMap = function(aaamap)
{
    //STUB
	//create hidden map in a div
	this.ve_map_div = document.createElement("div");
	this.ve_map_div.id = "ve_map_div";
	
	this.ve_map_div.style.visibility = "hidden";
	this.ve_map_div.style.position = "absolute";
	this.ve_map_div.style.width = "250px";
	this.ve_map_div.style.height = "250px";
	
	this.ve_bird_scene_id = null;
	
	this.g_map = aaamap;
	this.g_map_div = aaamap.getParentDiv();
	
    this.parent_div = document.getElementsByTagName("body")[0];
	this.parent_div.appendChild(this.ve_map_div);
	
	this.ve_map = null;
	
	this._onEndPanHandler = null;
    this._onChangeMapStyle = null;	
	
	this.control = null;
	this.explorer = null;
}

/*
 * AAAVirtualMap. To embedd a map call
 * embeddIn();
 * loadMap();
 */
MapControl2.AAAVirtualMap.prototype =
{
    /*****************************************
                Private Methods
    ******************************************/
    
    _getEndPanHandler : function()
    {
        var virtual_map_closure = this;
        
        var handler = function(e)
        {
            if (virtual_map_closure.ve_map.GetMapStyle() == VEMapStyle.Birdseye)
            {   
                virtual_map_closure.ve_map_div.style.visibility = "hidden";
                virtual_map_closure.birdscene_id = virtual_map_closure.ve_map.GetBirdseyeScene().GetID();
                virtual_map_closure.ve_map.SetMapStyle(VEMapStyle.Road);
            }else if (virtual_map_closure.ve_map.GetMapStyle() == VEMapStyle.Road)
            {   
                virtual_map_closure.ve_map.SetMapStyle(VEMapStyle.Birdseye);
            }
            
        };
        
        return handler;
    },
    
    _getChangeMapStyleHandler : function()
    {
        var virtual_map_closure = this;
        
        var handler = function(e)
        {
            if (e.mapStyle == "r")
            {
                var temp_loc = virtual_map_closure.ve_map.GetCenter();

                virtual_map_closure.ve_map.SetMapStyle(VEMapStyle.Birdseye);
            /*    if (navigator.appName != "Microsoft Internet Explorer")
                {
                    virtual_map_closure.ve_map.SetBirdseyeScene(virtual_map_closure.birdscene_id);
                } */
                virtual_map_closure.ve_map.SetBirdseyeScene(temp_loc);
                
                virtual_map_closure.ve_map_div.style.visibility = "visible";
                
                if(virtual_map_closure.explorer != null) 
                    virtual_map_closure.explorer.setLatLng(new GLatLng(temp_loc.Latitude, temp_loc.Longitude));
                else 
                    virtual_map_closure.addExplorer(temp_loc.Latitude, temp_loc.Longitude);
                
            }else if (e.mapStyle == "o")
            {   
                virtual_map_closure.ve_map_div.style.visibility = "visible";
            }
        }
        
        return handler;
    },
    
    _getObliqueEnterHandler : function()
    {
        var virtual_map_closure = this;
        
        var handler = function(e)
        {
            
            if(virtual_map_closure.ve_map.IsBirdseyeAvailable())
            {
                virtual_map_closure.ve_map_orientation = VEOrientation.North;
	
                virtual_map_closure.parent_div.removeChild(virtual_map_closure.unavailable);
                
                virtual_map_closure.ve_map.HideDashboard();
                virtual_map_closure.ve_map.SetBirdseyeScene(virtual_map_closure.starting_loc);
                
                virtual_map_closure.ve_map_div.style.visibility = "visible";
                
                virtual_map_closure.loadContent();
                virtual_map_closure.showControls();
                
                virtual_map_closure._onEndPanHandler = virtual_map_closure._getEndPanHandler();
                virtual_map_closure._onChangeMapStyle = virtual_map_closure._getChangeMapStyleHandler();
                
                virtual_map_closure.ve_map.AttachEvent("onendpan", virtual_map_closure._onEndPanHandler);
                virtual_map_closure.ve_map.AttachEvent("onchangemapstyle", virtual_map_closure._onChangeMapStyle);
            }
        };
        
        return handler;
    },
    
    /*****************************************
                Public Methods
    ******************************************/
    
    loadContent : function()
    {
        var trips = new Array();
        
        trips.concat(this.g_map._trips);
        trips.push(this.g_map._editableTrip);
        
        for (k in trips)
        {
            var trip = trips[k];
            
            //Add Routes
            var routes = trip.getRoutes(); 
            
            for (x in routes)
            {
                var gpoly = routes[x].getPolyline();
                var ve_vertices = new Array(gpoly.getVertexCount());
                
                for (var i = 0; i < gpoly.getVertexCount(); i++)
                {
                    var gvert = gpoly.getVertex(i);
                    ve_vertices[i] = new VELatLong(gvert.lat(), gvert.lng());
                }
                var shape = new VEShape(VEShapeType.Polyline, ve_vertices);
                var color = new VEColor(HexToR(routes[x]._polylineColor), HexToG(routes[x]._polylineColor), HexToB(routes[x]._polylineColor), 1.0);
                shape.SetLineColor(color);
                shape.SetTitle('Trip Polyline');
                shape.SetDescription('This Trip is not editable');
                this.ve_map.AddShape(shape);
            }
            
            //Add Markers
            var markers = trip.getMarkers();
            
            for (x in markers)
            {
                var pushpin = new VEShape(VEShapeType.Pushpin, new VELatLong(markers[x]._geoloc.lat, markers[x]._geoloc.lng));
                pushpin.SetCustomIcon(markers[x]._normalImage);
                this.ve_map.AddShape(pushpin);  
            }
            
            
        }
    },
    
    addExplorer : function(lat, lng)
    {
        if ( this.explorer == null)
        {
            this.explorer = new GMarker(new GLatLng(lat, lng));
            this.g_map.addOverlay(this.explorer);
        }
    },
    
    removeExplorer : function()
    {
        if (this.explorer != null) this.g_map.removeOverlay(this.explorer);
        this.explorer = null;
    },
    
    rotate : function(opposite)
    {
        switch(this.ve_map_orientation)
        {
           case VEOrientation.East: 
                if (opposite) this.ve_map_orientation = VEOrientation.North;
                else this.ve_map_orientation = (VEOrientation.South);
                break;
           case VEOrientation.West: 
                if (opposite) this.ve_map_orientation = (VEOrientation.South);
                else this.ve_map_orientation = (VEOrientation.North);
                break;
           case VEOrientation.North:  
                if (opposite) this.ve_map_orientation = (VEOrientation.West);
                else this.ve_map_orientation = (VEOrientation.East);
                break;
           default:      
                if (opposite) this.ve_map_orientation = (VEOrientation.East);
                else this.ve_map_orientation = (VEOrientation.West);
                break;
        }
        this.ve_map.SetBirdseyeOrientation(this.ve_map_orientation);
    },
    
	showControls : function()
	{
	    this.control = document.createElement("div"); 
        this.control.id = "VE_navigation";
        this.control.style.top ="5px"; 
        this.control.style.left = "5px"; 
        this.control.style.width = "20px";
        this.control.style.position = "relative";
    
        global_ve_map_handler = this;
    
        this.control.innerHTML = 
            '<img src="http://' + window.location.host + '/common/mapfiles/navigation.png" width="60" height="49" border="0" usemap="#map" />' +
            '<map name="map">'+
            '<area shape="circle" coords="11,25,11" onclick="global_ve_map_handler.rotate(true);"/>'+
            '<area shape="circle" coords="30,10,10" onclick="global_ve_map_handler.ve_map.ZoomIn();" />'+
            '<area shape="circle" coords="30,38,10" onclick="global_ve_map_handler.ve_map.ZoomOut();" />'+
            '<area shape="circle" coords="48,24,11" onclick="global_ve_map_handler.rotate(false);" />'+
            '</map>';
              
        this.parent_div.appendChild(this.control);
        this.control.style.zIndex = "10";
    
	},
	
	hideControls : function()
	{
	    if (this.control != null) this.parent_div.removeChild(this.control);
	    this.control = null;
	},

	embeddInDiv : function(div_id)
	{
	    if (!this.checkAvailability()) return;
	     
	    var div = document.getElementById(div_id);
	    this.parent_div.removeChild(this.ve_map_div);
	    div.appendChild(this.ve_map_div);
	    this.parent_div = div;
	    
	    this.unavailable = document.createElement("div"); 
        this.unavailable.style.position = "absolute";
        this.unavailable.innerHTML = "Microsoft is sorry, but no Bird's eye is available here";
        
        div.appendChild(this.unavailable);
	},
	
	removeFromDiv : function()
	{
	    if (this.ve_map == null) return;
	     
	    this.ve_map_div.style.visibility = "hidden";
	    
	    this.hideControls();
	    
	    //detach all events!
	    this.ve_map.DetachEvent("onobliqueenter", this._onObliqueEnterHandler);
	    if (this._onEndPanHandler != null) this.ve_map.DetachEvent("onendpan", this._onEndPanHandler);
        if (this._onChangeMapStyle != null) this.ve_map.DetachEvent("onchangemapstyle", this._onChangeMapStyle);
        
        this._onEndPanHandler = null;
        this._onChangeMapStyle = null;
        
	    this.removeExplorer();
	    
	    this.parent_div.removeChild(this.ve_map_div);
	    
	    //reattach to gmapdiv
	    this.parent_div = document.getElementsByTagName("body")[0];
	    this.parent_div.appendChild(this.ve_map_div);
	    //remove polyline and markers
	    
	},
	
	setLocation : function(geoloc)
	{
	    if (!this.checkAvailability()) return;
	    
	    var ve_loc = new VELatLong(geoloc.lat, geoloc.lng);
        this.ve_map.LoadMap(ve_loc, 17);
        this.starting_loc = ve_loc;
        this._onObliqueEnterHandler = this._getObliqueEnterHandler();
        this.ve_map.AttachEvent("onobliqueenter", this._onObliqueEnterHandler );
	},
	
	load : function(div, geoloc)
	{	
        var v_map_closure = this;
           
        if (checkVirtualEarthApi())
        {
            v_map_closure.embeddInDiv(div);
            v_map_closure.setLocation(geoloc);
        }else
        {
            loadVirtualEarthApi();
        
            var onApiLoaded = function()
            {
                if (checkVirtualEarthApi())
                {
                    v_map_closure.embeddInDiv(div);
                    v_map_closure.setLocation(geoloc);
                }    
            }
            self.ve_api.onreadystatechange = function () 
            {
                if (this.readyState == 'complete') onApiLoaded();
            }
            self.ve_api.onload = onApiLoaded;
        }
    },
    
    checkAvailability : function()
    {
        if (checkBrowserSupport() && checkVirtualEarthApi())
	    {
	        if (this.ve_map == null) this.ve_map = new VEMap("ve_map_div");
	        return true;
	    }
	    else return false;
    }	
}